import datetime
from typing import List, Dict

from sqlalchemy import Boolean, Column, DateTime, Integer, String, Index, text, ForeignKey, JSON, TEXT, and_
from sqlalchemy.orm import Session, relationship
from sqlalchemy.orm import Session

from common.database import Base
from common.database import SessionMixin


class MonitorLogExcludeKeyword(Base, SessionMixin):
    __tablename__ = 'monitor_log_exclude_keyword'
    service_name = Column(String(128), nullable=False, comment="服务名称")  # 策略名称等于应用名称
    username = Column(String(128), nullable=False, comment="需求人")
    exclude_keyword = Column(TEXT, nullable=False, comment="排除关键字")
    is_active = Column(Boolean, default=text('true'), nullable=False, comment="屏蔽关键字状态")
    effective_datetime = Column(DateTime, nullable=False, comment="关键字屏蔽生效时间")
    expiration_datetime = Column(DateTime, nullable=False, comment="关键字屏蔽失效时间")
    comment = Column(String(255), nullable=True, comment="屏蔽说明")
    monitor_log_service_uuid = Column(Integer, ForeignKey('monitor_log_service.uuid'), nullable=False, comment="监控日志策略uuid")
    # keyword2service = relationship('MonitorLogExcludeKeyword', backref='service2keyword')
    create_time = Column(DateTime, default=datetime.datetime.now, nullable=False, comment="创建时间")
    update_time = Column(DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now, nullable=False,
                         comment="更新时间")

    __table_args__ = (
        Index('idx_monitor_log_exclude_keyword_uuid', 'uuid', unique=True),
        Index('idx_monitor_log_exclude_keyword_expiration_datetime', 'expiration_datetime', unique=False),
        {
            'mysql_engine': 'innodb',
            'mysql_charset': 'utf8mb4',
            'mysql_collate': 'utf8mb4_unicode_ci',
            'extend_existing': True,
            'mysql_row_format': 'dynamic',
        }
    )

    def __repr__(self):
        return "<uuid='{}',username='{}',keyword='{}'>".format(self.uuid, self.username, self.keyword)

    @classmethod
    def get_policy_by_policy_name(cls, db: Session, service_name):
        return db.query(cls).filter(cls.policy_name == service_name).to_dict_first()

    @classmethod
    def get_exclude_keyword_by_service_name(cls, db: Session, service_name: str, date_time: str) -> List:
        return db.query(cls).with_entities(cls.exclude_keyword).filter(
            and_(cls.service_name == service_name, cls.expiration_datetime > date_time)).to_dict()

    # @classmethod
    # def get_by_app_name(cls, db: Session, app_name: str) -> Dict:
    #     return db.query(cls).filter(cls.app_name == app_name).to_dict_first()
    #
    # @classmethod
    # def get_policy_by_app_name(cls, db: Session, app_name: str) -> Dict:
    #     app = db.query(cls).filter(cls.app_name == app_name).first()
    #     return cls.to_dict(app.app2policy) if app else {}
    #
    # @classmethod
    # def get_entries(cls, db: Session) -> List[Dict]:
    #     return db.query(cls).outerjoin(
    #         MonitorLogPolicy, cls.monitor_log_policy_uuid == MonitorLogPolicy.uuid).with_entities(
    #         cls.uuid.label('uuid'), cls.app_name.label('app_name'), cls.app_log_status.label('app_log_status'),
    #         MonitorLogPolicy.exclude_keywords.label('exclude_keywords'),
    #         MonitorLogPolicy.alarm_threshold.label('alarm_threshold'),
    #         MonitorLogPolicy.is_maintain.label('is_maintain'),
    #         MonitorLogPolicy.alarm_plan.label('alarm_plan'),
    #         MonitorLogPolicy.maintain_begin_time.label('maintain_begin_time'),
    #         MonitorLogPolicy.maintain_end_time.label('maintain_end_time'),
    #         MonitorLogPolicy.notice_users.label('notice_users'),
    #         MonitorLogPolicy.create_time.label('create_time'),
    #         MonitorLogPolicy.update_time.label('update_time')).to_dict()
    #
    # @classmethod
    # def get_policy_paginate(cls, db: Session, page, per_page) -> List[Dict]:
    #     return db.query(cls).outerjoin(
    #         MonitorLogPolicy, cls.monitor_log_policy_uuid == MonitorLogPolicy.uuid).with_entities(
    #         cls.uuid.label('uuid'), cls.app_name.label('app_name'), cls.app_log_status.label('app_log_status'),
    #         MonitorLogPolicy.exclude_keywords.label('exclude_keywords'),
    #         MonitorLogPolicy.alarm_threshold.label('alarm_threshold'),
    #         MonitorLogPolicy.is_maintain.label('is_maintain'),
    #         MonitorLogPolicy.alarm_plan.label('alarm_plan'),
    #         MonitorLogPolicy.maintain_begin_time.label('maintain_begin_time'),
    #         MonitorLogPolicy.maintain_end_time.label('maintain_end_time'),
    #         MonitorLogPolicy.notice_users.label('notice_users'),
    #         MonitorLogPolicy.create_time.label('create_time'),
    #         MonitorLogPolicy.update_time.label('update_time')).paginate(page, per_page)
